<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link type="text/css" rel="stylesheet" nonce="${nonce}" href="${iconFontCss}">
  <style>


  </style>
  <title>Config Edit</title>
</head>
<body style="display: flex;flex-direction: column;height: 100%;">

<div id="app">
  <section class="big-section" v-if="config.version">
    <div class="title-box">
      <h1 class="title">VPA 会话设置</h1>
      <label slot="label">请为 VPA 运行设置会话信息，包括 host 和 yhtAccessToken。</label>
    </div>

    <vscode-radio-group orientation="vertical" id="sessions" class="border" style="padding: 20px"
      v-if="Object.keys(config.base.session.options).length"
      @change="sessionChange">
      <template v-for="(s,k) in config.base.session.options">
        <vscode-radio :id="'sr'+k" :value="k" checked v-if="config.base.session.use === k"
          v-html="renderSessionItem(s,k)" class="session-radio"></vscode-radio>
        <vscode-radio :id="'sr'+k" :value="k" v-else v-html="renderSessionItem(s,k)"
          class="session-radio"></vscode-radio>
      </template>
    </vscode-radio-group>

    <div v-else class="border" style="background-color: var(--input-background);padding: 20px">
      <span style="color: var(--vscode-foreground);opacity: .8">暂无会话配置，请点击下面的按钮开始新增。</span>
    </div>


    <div style="flex-direction: column;" id="add-view" v-if="state.isAddSession">

      <h2 class="title">新增会话</h2>
      <div style="display: flex;">
        <div style="display: flex;flex-direction: column;padding: 20px;width:66%;" class="border">
          <vscode-text-field class="text-field" placeholder="https://"
            :value="form.base.host" @input="event => form.base.host = event.target.value">
            <span>会话 host</span>
          </vscode-text-field>
          <vscode-text-field class="text-field" placeholder="请输入yhtAccessToken" style="margin-top: 10px"
            :value="form.base.yhtAccessToken" @input="event => form.base.yhtAccessToken = event.target.value">
            <span >yhtAccessToken</span>
          </vscode-text-field>

          <vscode-text-field class="text-field" placeholder="可选，不填写将自动随机生成" style="margin-top: 10px"
            :value="form.base.desc" @input="event => form.base.desc = event.target.value">
            <span>配置名称</span>
          </vscode-text-field>
          <div style="margin-top: 10px">
            <vscode-button id="session-save" appearance="primary" style="margin-right: 10px" @click="setAdd(2)">
              保存
            </vscode-button>
            <vscode-button id="session-cancel" appearance="secondary" @click="setAdd(3)">取消</vscode-button>
          </div>
        </div>

        <div style="display: flex;flex-direction: column;align-items: center;justify-content: center;flex: 1">
          <span style="margin-bottom: 10px;color: var(--vscode-foreground)">使用友空间扫码，快速输入</span>
          <div class="qrcode" id="canvas">
          </div>
        </div>
      </div>
    </div>
    <div style="margin: 20px" id="show-add-session" v-else>
      <vscode-button @click="setAdd(1)"> 新增会话 <span slot="start" class="icon iconfont icon-add"></span>
      </vscode-button>
    </div>
  </section>


</div>


<script defer nonce="${nonce}" src="${vueJs}"></script>
<script defer nonce="${nonce}" src="${QRCodeJs}"></script>
<script nonce="${nonce}" src="${webviewUri}"></script>


<script>

  document.addEventListener('DOMContentLoaded', () => {
    console.log('&&', '启动')
    init()
  })

  let userInfo = {}
  let vm

  function init () {
    vm = new Vue({
      el: '#app',
      data: {
        state: {
          isAddSession: false,
          isAddDevMap: false
        },
        config: {},
        form: {
          base: {
            host: '',
            yhtAccessToken: '',
            desc: ''
          },
          devMap: {
            rid: '',
            src: '',
            desc: ''
          }
        }
      },
      mounted () {
        addMsgListener()
        window.vueOnMounted()
      },
      watch: {
        state: {
          handler (state) {
            if (state.isAddSession) {
              this.waitQR(state.isAddSession)
            }
          },
          deep: true
        }
      },
      methods: {
        updateJson () {
          clientChannel.call('host-msg', {
            type: 'update',
            data: this.config
          })
        },
        renderSessionItem (s, k) {
          return `<div class="session-item">
            <div>
            <span class="session-tag">${k}</span></div>
            <div class="session-info">
            ${s.host} ${s.yhtAccessToken.substr(0, 8)}</div>
            <div>        </div>
            </div>`
        },
        setAdd (type) {
          if (type === 1) { // 新增
            this.state.isAddSession = true
          } else if (type === 2) { // 保存
            this.sessionSave()
          } else if (type === 3) {// 取消
            this.state.isAddSession = false
          }
        },
        setDevMapAdd (type) {
          if (type === 1) { // 新增
            this.state.isAddDevMap = true
          } else if (type === 2) { // 保存
            this.devMapSave()
          } else if (type === 3) {// 取消
            this.state.isAddDevMap = false
          }
        },
        devMapSave () {
          let {
            rid,
            src,
            desc
          } = this.form.devMap

          if (!src) {
            clientChannel.call('host-msg', {
              type: 'error',
              data: '源码入口不能为空'
            })
            return
          } else {

            if (rid) {
              if (!/^[0-9]{19}$/.test(rid)) {
                clientChannel.call('host-msg', {
                  type: 'error',
                  data: 'vpaResourceID 必须是19位数字'
                })
                return
              }
            } else {
              rid = parseInt(Date.now() * Math.random()).toString(32)
            }

            if (src) { // 入口不能以数字开头，以及不能包含除了 / 之外特殊符号
              if (/^[0-9]/.test(src) || /[^\w\/]/.test(src)) {
                clientChannel.call('host-msg', {
                  type: 'error',
                  data: '源码入口不能以数字开头，以及不能包含除了 / 之外特殊符号'
                })
                return
              }

            }

          }

          this.config.devMap.list[rid] = {
            src,
            desc: getDesc()
          }
          this.state.isAddDevMap = false

          this.updateJson()

          function getDesc () {
            if (desc) {
              return desc
            } else {
              // 解释一下这个正则：src.replace(/^src\/|^\/src\//, '') 用来去掉 src/ 或者 /src/ 前缀
              // 然后 split('/').join('-') 用来把 / 转成 -
              // 然后 split('.')[0] 用来去掉后缀
              // 然后 replace(/-index$/, '') 用来去掉 -index 后缀
              // 最后加上一个 rid 的后四位，用来区分不同的卡片
              return src.replace(/^src\/|^\/src\//, '').split('/').join('-').split('.')[0].replace(/-index$/, '') + '@' + rid.substring(rid.length - 4)
            }
          }
        }
        ,
        delDevMap (rid) {
          delete this.config.devMap.list[rid]
          // 更新视图
          this.$forceUpdate()
          this.updateJson()
        },
        actionInDevMap (rid, type) {
          const item = this.config.devMap.list[rid]

          clientChannel.call('host-msg', {
            type: type,
            data: item.src
          })
        },
        setPanelActiveId (id) {
          this.$refs.panel.setAttribute('activeid', id)
        }
        ,
        sessionChange (e) {
          if (this.config.base.session.use !== e.target.value) { // 避免重复触发
            this.config.base.session.use = e.target.value
            this.updateJson()
          }
        }
        ,
        sessionSave () {
          const {
            desc,
            host,
            yhtAccessToken
          } = this.form.base

          if (!host || !yhtAccessToken) {
            clientChannel.call('host-msg', {
              type: 'error',
              data: 'host 和 yhtAccessToken 不能为空'
            })
            return
          }

          this.config.base.session.use = desc

          this.config.base.session.options[desc] = {
            host,
            yhtAccessToken,
            userInfo
          }

          this.state.isAddSession = false
          setTimeout(() => { // 为了让 radio 选中
            document.getElementById('sr' + desc).checked = true
            userInfo = {}
          }, 0)

          this.updateJson()

        }
        ,
        waitQR (val) {
          clientChannel.call('host-msg', {
            type: 'waitQR',
            data: val
          }).then(res => {
            if (res.code === 0) {
              if (val) {// 打开的时候
                const text = `http://${res.ips[0]}:3344/h`
                document.getElementById('canvas').appendChild(new AraleQRCode({
                  text,
                  size: 168,
                  correctLevel: 0
                }))
              } else {// 关闭的时候。正常这应该显示：‘监听已经关闭’
                console.log(res)
              }
            } else {
              clientChannel.call('host-msg', {
                type: 'error',
                text: res.msg
              })
            }
          }).catch(e => {
            console.error(e)
          })

        }
      }
    })
  }

  function addMsgListener () {
    console.log('&&', '添加消息监听', window.clientChannel)
    window.clientChannel.on('client-api', async param => {

      const {
        type,
        data
      } = param

      console.log('客户端收到 client-api', type)

      if (type === 'init') {

        try {
          const config = JSON.parse(data)
          updateContent(config)
        } catch (e) {
          console.error(e)
        }

      } else if (type === 'land') {
        const {
          name,
          info: {
            host,
            yhtAccessToken
          }
        } = data

        const {
          name: uName,
          userId,
          avatar,
          mobile
        } = data.info.userInfo

        userInfo = {
          name: uName,
          userId,
          avatar,
          mobile
        }

        if (data.action) {
          vm.form.base.host = host
          vm.form.base.yhtAccessToken = yhtAccessToken
          vm.form.base.desc = name + '-' + userInfo.userId

          if (data.action === '接收并保存') {
            vm.sessionSave()
            clear()
          }

        } else {
          clear()
        }

        function clear () {
          vm.form.base.host = ''
          vm.form.base.yhtAccessToken = ''
          vm.form.base.desc = ''
        }

      } else if (type === 'open') {
        console.log('open~', data)
        const { type } = data
        if (type === 'config-error') {
          vm.state.isAddSession = true
          vm.setPanelActiveId('base')
        }
      }
    })

    window.clientChannel.call('host-msg', {
      type: 'ccIsOk'
    })

  }

  function updateContent (config) {
    console.log('updateContent', config)
    vm.config = config
  }


</script>

</body>
</html>
